<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clearFilters"
    />
    <div v-if="meta.indexOf('UserAdd') > -1" class="doumee-table-buttons">
      <el-button
        v-preventReClick
        type="primary"
        @click="toAccountAdd(0)"
      >新增</el-button>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        label="登陆账号"
        prop="username"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="用户昵称"
        prop="name"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="真实姓名"
        prop="realName"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="手机号"
        prop="mobile"
        show-overflow-tooltip
        min-width="140"
      />
      <el-table-column
        align="center"
        label="关联角色"
        prop="roleName"
        show-overflow-tooltip
        min-width="200"
      />
      <el-table-column
        align="center"
        label="用户说明"
        prop="info"
        show-overflow-tooltip
        min-width="200"
      />
      <el-table-column
        align="center"
        fixed="right"
        label="状态"
        min-width="80"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="'1'"
            :inactive-value="'0'"
            :disabled="meta.indexOf('UserEdit') == -1"
            @change="toAccountStatus($event, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        min-width="220"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="meta.indexOf('UserEdit') > -1"
              v-preventReClick
              type="text"
              @click="toAccountAdd(1, scope.row)"
            >编辑</el-button>
            <el-button
              v-if="meta.indexOf('UserResetPw') > -1"
              v-preventReClick
              type="text"
              @click="toAccountRepassword(scope.row.userId)"
            >重置密码</el-button>
            <el-button
              v-if="meta.indexOf('UserDel') > -1"
              v-preventReClick
              type="text"
              style="color: red"
              @click="toAccountDelete(scope.row.userId)"
            >删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />

    <!-- 新增 编辑 用户 -->
    <el-dialog
      :close-on-click-modal="modalDialog"
      :lose-on-press-escape="modalDialog"
      :title="formAddAccount.userId ? '编辑用户' : '新增用户'"
      :visible.sync="showAddAccount"
      width="800px"
      @closed="cancelAddAccount"
    >
      <el-form
        ref="ruleForm"
        :model="formAddAccount"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="登陆账号" prop="username">
          <el-input v-model="formAddAccount.username" :disabled="Boolean(formAddAccount.userId)" maxlength="20" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input v-model="formAddAccount.name" maxlength="20" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="formAddAccount.realName" maxlength="20" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="formAddAccount.mobile"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="formAddAccount.identityNumber" maxlength="20" />
        </el-form-item>
        <el-form-item label="关联角色" prop="roleId">
          <el-select
            v-model="formAddAccount.roleId"
            value-key="id"
            placeholder="选择角色"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in roleListData"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户说明">
          <el-input v-model="formAddAccount.info" />
        </el-form-item>
        <el-form-item label="用户状态">
          <el-switch
            v-model="formAddAccount.status"
            :active-value="'1'"
            :inactive-value="'0'"
          />
        </el-form-item>
        <div class="tip-style noLeft">
          <span>提示：1.登录账号如有修改，系统重置用户密码为默认密码；2:密码为字典值配置中设置的默认密码</span>
        </div>
      </el-form>
      <span slot="footer">
        <el-button @click="cancelAddAccount">取消</el-button>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="confirmAddAccount"
        >确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  uploadFile,
  venueList,
  roleListPost,
  accountListPost,
  syncUserToDev,
  accountAddPost,
  accountRepassword,
  accountStatus,
  accountEditPost,
  accountDelPost,
  accountStatusChangePost,
  accountDetailPost
} from '@/api'
import Pagination from '@/components/paginations'
import { queryFormConfig } from './config'
export default {
  components: {
    Pagination
  },
  data() {
    return {
      queryFormConfig,
      modalDialog: this.$store.state.app.dialog,
      subLoading: false,
      dialogCropperVisible: false,
      param: {},
      meta: [],
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'USER_IMG'
      },
      cur_page: 1,
      venueListData: [],
      roleListData: [],
      list: [],
      filters: {
        username: ''
      },
      pagination: {
        page: 1,
        rows: 10
      },
      total: 0,
      showAddAccount: false,
      imageList: [],
      formAddAccount: {
        username: '',
        realName: '',
        mobile: '',
        roleId: '',
        status: '1',
        info: ''
      },
      printerListb: [],
      rules: {
        username: [
          { required: true, message: '请输入登陆账号', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        identityNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          {
            required: true,
            pattern:
              /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
            message: '请输入正确的身份证号',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        roleId: [
          {
            required: true,
            message: '请选择关联角色',
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {
    defaultPsd() {
      return this.$store.state.user.dictList.find(i => i.code === 'PLAT_DEFAULT_PW')
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getList(1)
    this.getRoleList()
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    tbry(userId) {
      syncUserToDev({
        param: {
          type: '0',
          userType: '0',
          userId
        }
      }, sessionStorage.getItem('venueId')).then(res => {
        if (res.errorCode === '000000') {
          this.$message.success('同步成功')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 获取角色列表
    getRoleList() {
      roleListPost({ param: {}}).then((res) => {
        if (res.errorCode !== '000000') return
        this.roleListData = res.recordList
      })
    },
    // 清空筛选项
    clearFilters() {
      this.filters = {}
      this.getList(1)
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    // 获取账号列表
    getList(page) {
      const { pagination, filters: param } = this
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      this.listLoading = true
      accountListPost({ pagination, param }).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          for (const i in res.recordList) {
            const { stadiumList } = res.recordList[i]
            const { roleList } = res.recordList[i]
            res.recordList[i].stadiumList_ = []
            for (const j in stadiumList) {
              res.recordList[i].stadiumList_.push(stadiumList[j].name)
            }
            res.recordList[i].stadiumList_ =
              res.recordList[i].stadiumList_.join('/')

            res.recordList[i].roleList_ = []
            for (const j in roleList) {
              res.recordList[i].roleList_.push(roleList[j].name)
            }
            res.recordList[i].roleList_ = res.recordList[i].roleList_.join('/')
          }
          this.list = res.recordList
          this.total = res.totalCount
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    change() {
      const { venueListData } = this
      const param = { ...this.formAddAccount }
      param.list = []
      for (const i in venueListData) {
        if (venueListData[i].checked) {
          param.list.push(venueListData[i].id)
        }
      }
      this.$set(this.formAddAccount, 'list', param.list)
    },
    // 重置密码
    toAccountRepassword(userId) {
      accountRepassword({ param: { userId }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.$message.success('重置密码成功')
      })
    },
    // 启用禁用
    toAccountStatus(status, row) {
      accountStatusChangePost({ param: { status, userId: row.userId }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.getList()
        this.$message.success('更新状态成功')
      }, () => {
        this.getList()
      })
    },
    // 新增 编辑 用户
    toAccountAdd(type, row) {
      this.showAddAccount = true
      // 编辑 数据回显
      if (row) {
        accountDetailPost({ param: { userId: row.userId }}).then(res => {
          this.formAddAccount = { ...res.record }
        })
        this.$nextTick(() => {
          this.$refs.ruleForm.clearValidate()
        })
      }
    },
    // 取消 新增 编辑 用户
    cancelAddAccount() {
      for (const item of this.venueListData) {
        item.checked = false
      }
      this.formAddAccount = {
        username: '',
        realName: '',
        mobile: '',
        roleIds: [],
        list: [],
        status: '1',
        info: ''
      }
      this.showAddAccount = false
    },
    // 确认新增 编辑 用户
    confirmAddAccount() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const param = { ...this.formAddAccount }
          this.subLoading = true
          if (param.userId) {
            accountEditPost({ param }).then((res) => {
              this.subLoading = false
              if (res.errorCode !== '000000') return
              this.showAddAccount = false
              this.getList(1)
            }, () => {
              this.subLoading = false
            })
          } else {
            accountAddPost({ param }).then((res) => {
              this.subLoading = false
              if (res.errorCode !== '000000') return
              this.showAddAccount = false
              this.getList(1)
            }, () => {
              this.subLoading = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除用户
    toAccountDelete(userId) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 删除绑定角色
          accountDelPost({ param: { userId }}).then((resss) => {
            if (resss.errorCode !== '000000') return
            this.$message.success('删除成功')
            this.getList(1)
          })
        })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>

